<?php

namespace app\admin\controller;

use app\admin\validate\OrderValidate;
use app\service\MemberService;
use app\service\OrderService;
use think\exception\ValidateException;

class Order extends Admin
{

    public function __construct(OrderService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "合约订单列表");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $where = [];
        if (!empty($params["buy_time"])) {
            $between = explode(" - ", $params["buy_time"]);
            if (count($between) == 2) {
                $where[] = ['buy_time', 'between', [$between[0], $between[1]]];
            }
        }
        $memberId = $params["member_id"] ?? 0;
        $memberIds = [];
        $email = $params["email"] ?? "";
        if (!empty($email)) {
            $memberService = $this->app->make(MemberService::class);
            $memberIds = $memberService->Column([["email", "like", "%$email%"]], "id");
            if (empty($memberIds)) {
                $ret = ["rows" => [
                    "total" => 0,
                    "list" => [],
                ]];
                $this->result($ret);
            }
        }
        if (!empty($memberId)) {
            array_push($memberIds, $memberId);
        }
        if (!empty($memberIds)) {
            $where[] = ['member_id', 'in', $memberIds];
        }
        $isWin = $params["is_win"] ?? 0;
        if (!empty($isWin)) {
            $where[] = ['is_win', '=', $isWin];
        }
        $status = $params["status"] ;
        if (!empty($status)) {
            $where[] = ['status', '=', $status];
        }
        $ret = $this->service->getList($where, ["*"], ["member", "market"]);
        int_to_string($ret["rows"]["list"], ["status" => ["-1" => "无效结算", "1" => "结算中", "2" => "已经结算"]]);
        $this->result($ret);
    }

    public function set()
    {
        $data = $this->request->post();
        try {
            validate(OrderValidate::class)->scene("set")->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->set($data["id"], $data["control"]);
        if (!empty($ret)) {
            $this->success("设置成功");
        }
        $this->error("设置失败");

    }

}